package com

import (
	"net"
	"os/exec"
	"strconv"
	"strings"
)

//获取本地IPV4地址
func GetLocalIPv4s() ([]string, error) {
	var ips []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ips, err
	}

	for _, a := range addrs {
		// 检查ip地址判断是否回环地址
		if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
			ips = append(ips, ipNet.IP.String())
		}
	}

	return ips, nil
}

//获取本地网卡地址
func GetLocalMacs() ([]string, error) {
	var macs []string
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return macs, err
	}

	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags&net.FlagUp) != 0 && (netInterfaces[i].Flags&net.FlagLoopback) == 0 {
			addrs, _ := netInterfaces[i].Addrs()
			for _, address := range addrs {
				ipNet, ok := address.(*net.IPNet)

				if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
					// 如果IP是全局单拨地址，则返回MAC地址
					mac := netInterfaces[i].HardwareAddr.String()
					macs = append(macs, mac)
				}
			}
		}
	}
	return macs, nil
}

//获取IPV4及网卡地址
func GetLocalIPv4sMacs() ([]string, error) {
	var macs []string
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return macs, err
	}

	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags&net.FlagUp) != 0 && (netInterfaces[i].Flags&net.FlagLoopback) == 0 {
			addrs, _ := netInterfaces[i].Addrs()
			for _, address := range addrs {
				ipnet, ok := address.(*net.IPNet)
				//fmt.Println(ipnet.IP)
				if ok && ipnet.IP.IsGlobalUnicast() {
					// 如果IP是全局单拨地址，则返回MAC地址
					mac := netInterfaces[i].HardwareAddr.String()
					macs = append(macs, ipnet.IP.String()+"/"+mac)
				}
			}
		}
	}
	return macs, nil
}

//获取网卡数量
func GetLocalNetCount() int {
	order2cmd := "ls /sys/class/net/ |wc -l"
	out, err := exec.Command("/bin/bash", "-c", order2cmd).CombinedOutput()
	if err != nil {
		return 0
	}
	out2string := strings.TrimSpace(string(out))
	out2int, _ := strconv.Atoi(out2string)
	return out2int - 1
}
